package com.example.weight.householdWaste;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.util.Utility;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ChangeWaterActivity extends AppCompatActivity {

    private String name, type, factory;

    private EditText deodorant, freshener, water, sprayNum, startTime, endTime;

    private TextView discharge;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_water);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        type = previousIntent.getStringExtra("type");
        factory = previousIntent.getStringExtra("factory");

        deodorant = findViewById(R.id.change_water_deodorant);
        freshener = findViewById(R.id.change_water_freshener);
        water = findViewById(R.id.change_water_addWater);
        sprayNum = findViewById(R.id.change_water_sprayer);
        startTime = findViewById(R.id.change_water_start_time);
        endTime = findViewById(R.id.change_water_end_time);
        discharge = findViewById(R.id.change_water_discharge_text);

        TitleBar titleBar = findViewById(R.id.change_water_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/shlj/deodorizationtowerWaterChange"+type+"/findForm" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONObject data = jsonObject.getJSONObject("data");
                                    String temp = data.getString("deodorant");
                                    if (temp.equals("null"))
                                        deodorant.setHint("未填写");
                                    else
                                        deodorant.setText(temp);
                                    temp = data.getString("freshener");
                                    if (temp.equals("null"))
                                        freshener.setHint("未填写");
                                    else
                                        freshener.setText(temp);
                                    temp = data.getString("cleanNozzleNumber");
                                    if (temp.equals("null"))
                                        sprayNum.setHint("未填写");
                                    else
                                        sprayNum.setText(temp);
                                    temp = data.getString("waterAddition");
                                    if (temp.equals("null"))
                                        water.setHint("未填写");
                                    else
                                        water.setText(temp);
                                    temp = data.getString("cleanFillerTime");
                                    if (temp.equals("null"))
                                        startTime.setHint("未填写");
                                    else
                                        startTime.setText(temp);
                                    temp = data.getString("fillerEndTime");
                                    if (temp.equals("null"))
                                        endTime.setHint("未填写");
                                    else
                                        endTime.setText(temp);
                                    String waterReduceTime = data.getString("waterReduceTime");
                                    discharge.setText(discharge.getText().toString().concat(waterReduceTime));
                                    Toast.makeText(ChangeWaterActivity.this,
                                            "今日已填写此表", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(ChangeWaterActivity.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);

        startTime.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Calendar calendar = Calendar.getInstance();
                int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
                int MINUTE = calendar.get(Calendar.MINUTE);

                @SuppressLint({"SetTextI18n", "DefaultLocale"})
                TimePickerDialog timePickerDialog = new TimePickerDialog(ChangeWaterActivity.this, 2,
                        (view1, hourOfDay, minute) ->
                                startTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                        ,HOUR
                        ,MINUTE
                        ,true);
                timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        startTime.clearFocus();
                    }
                });
                timePickerDialog.show();
            }
        });
        endTime.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Calendar calendar = Calendar.getInstance();
                int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
                int MINUTE = calendar.get(Calendar.MINUTE);

                @SuppressLint({"SetTextI18n", "DefaultLocale"})
                TimePickerDialog timePickerDialog = new TimePickerDialog(ChangeWaterActivity.this, 2,
                        (view1, hourOfDay, minute) ->
                                endTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                        ,HOUR
                        ,MINUTE
                        ,true);
                timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        endTime.clearFocus();
                    }
                });
                timePickerDialog.show();
            }
        });
    }

    @SuppressLint({"SetTextI18n", "DefaultLocale"})
    public void selectStartTime(View view) {
        Calendar calendar = Calendar.getInstance();
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);

        new TimePickerDialog(this, 2, (view1, hourOfDay, minute) ->
                startTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                ,HOUR
                ,MINUTE
                ,true).show();
    }

    @SuppressLint({"SetTextI18n", "DefaultLocale"})
    public void selectEndTime(View view) {
        Calendar calendar = Calendar.getInstance();
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);

        new TimePickerDialog(this,  2, (view1, hourOfDay, minute) ->
                endTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                ,HOUR
                ,MINUTE
                ,true).show();
    }

    public void beginReducingWater(View view) {
        new AlertDialog.Builder(this)
                .setTitle("是否开始放水")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) -> {}))
                .setPositiveButton("确定", (dialog, which) -> {
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/shlj/deodorizationtowerWaterChange"+type+"/beginReducingWater";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.d("zys", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");

                                        if (code.startsWith("2")) {
                                            @SuppressLint("SimpleDateFormat")
                                            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm" );
                                            String temp = discharge.getText().toString();
                                            discharge.setText(temp.concat(sdf.format(new Date())));

                                            Toast.makeText(ChangeWaterActivity.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        }
                                        else
                                            Toast.makeText(ChangeWaterActivity.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(ChangeWaterActivity.this,
                                    "失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            @SuppressLint("SimpleDateFormat") 
                            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm" );

                            Map<String, String> map=new HashMap<>();
                            map.put("water_reduce_time", sdf.format(new Date()));
                            map.put("recording_person", name);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    public void beginAddingWater(View view) {
        if (!Utility.isNumeric(deodorant.getText().toString())) {
            Toast.makeText(this, "除臭剂请填写数字", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!Utility.isNumeric(freshener.getText().toString())) {
            Toast.makeText(this, "清新剂请填写数字", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!Utility.isNumeric(water.getText().toString())) {
            Toast.makeText(this, "加水量请填写数字", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("是否开始加水")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) -> {}))
                .setPositiveButton("确定", (dialog, which) -> {
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/shlj/deodorizationtowerWaterChange"+type+"/beginAddingWater";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");

//                                        deodorant.setText("");
//                                        freshener.setText("");

                                        if (code.startsWith("2"))
                                            Toast.makeText(ChangeWaterActivity.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(ChangeWaterActivity.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(ChangeWaterActivity.this,
                                    "失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            @SuppressLint("SimpleDateFormat")
                            SimpleDateFormat sdf =new SimpleDateFormat("HH:mm" );

                            Map<String, String> map=new HashMap<>();
                            map.put("water_add_time", sdf.format(new Date()));
                            map.put("water_addition", water.getText().toString());
                            map.put("deodorantstr", deodorant.getText().toString());
                            map.put("freshenerstr", freshener.getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    public void beginCleaningStuffing(View view) {
        if (!Utility.isNumeric(sprayNum.getText().toString())) {
            Toast.makeText(this, "喷头数请填写数字", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("是否开始清理填料")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) -> {}))
                .setPositiveButton("确定", (dialog, which) -> {
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/shlj/deodorizationtowerWaterChange"+type+"/beginCleaningStuffing";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");

                                        sprayNum.setText("");

                                        if (code.startsWith("2"))
                                            Toast.makeText(ChangeWaterActivity.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(ChangeWaterActivity.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(ChangeWaterActivity.this,
                                    "失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            @SuppressLint("SimpleDateFormat") 
                            SimpleDateFormat sdf =new SimpleDateFormat("HH:mm" );

                            Map<String, String> map=new HashMap<>();
                            String temp = startTime.getText().toString();
                            map.put("clean_filler_time", temp.equals("")?sdf.format(new Date()):temp);
                            map.put("filler_end_time", endTime.getText().toString());
                            map.put("clean_nozzle_numberstr", sprayNum.getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

//    public void save(View view) {
//        new AlertDialog.Builder(this)
//                .setTitle("确定保存吗？")
//                .setCancelable(false)
//                .setNegativeButton("取消", ((dialog, which) ->
//                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
//                .setPositiveButton("确定", (dialog, which) ->{
//                    // 提交表单
//                    RequestQueue queue = Volley.newRequestQueue(this);
//                    String url = Config.url + "/shlj/deodorizationtowerWaterChange/add";
//
//                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
//                            new Response.Listener<String>() {
//                                @Override
//                                public void onResponse(String response) {
//                                    Log.d("zys", response);
//                                    try {
//                                        JSONObject jsonObject = new JSONObject(response);
//                                        String code = jsonObject.getString("code");
//                                        comment.setText("");
//
//                                        if (code.startsWith("2"))
//                                            Toast.makeText(ChangeWaterActivity.this,
//                                                    "保存成功", Toast.LENGTH_SHORT).show();
//                                        else
//                                            Toast.makeText(ChangeWaterActivity.this,
//                                                    "保存失败", Toast.LENGTH_SHORT).show();
//                                    } catch (JSONException e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            }, new Response.ErrorListener() {
//                        @Override
//                        public void onErrorResponse(VolleyError error) {
//                            Toast.makeText(ChangeWaterActivity.this,
//                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
//                        }
//                    }) {
//                        @Override
//                        protected Map<String, String> getParams() {
//                            Map<String, String> map=new HashMap<>();
//                            String temp = comment.getText().toString();
//                            map.put("remarks", temp);
//                            return map;
//                        }
//                    };
//                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
//                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//                    queue.add(stringRequest);
//                })
//                .show();
//    }
}
